#-- coding:UTF-8 -- 
# 用户注册登录服务器
#(env375) wuchunlong@wuchunlong mysite$ python3 userServer.py

import sys
import os
import time
import socket
import datetime
import threading
import django
import json
# python使用django数据库，下面两条语句是必须的
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

from myAPI.strToDct import toDict
from myAPI.getServerIP import getServerIP
from blog.models import UserInfo

from djDB_UserInfo_Msg_API_V1 import * #addMac, is_name_pass, find_all

USER_RECEIVE_PORT = 3427 #客户端注册登录端口 
SERVER_IP = getServerIP() #获取本机ip地址 192.168.31.18

CMD_REGISTER_NO = 4  #注册失败
CMD_LOGIN_NO =    5  #登录失败
CMD_REGISTER_OK = 6  #注册成功
CMD_LOGIN_OK =    7  #登录成功
CMD_REGISTER =    8 # 注册
CMD_LOGIN =       9 # 登录


DCT_LOGIN_OK = "{'msgCMD':%s, 'CMD_LOGIN_RECE':%s}"%(CMD_LOGIN, CMD_LOGIN_OK) #登录成功关键字
DCT_LOGIN_NO = "{'msgCMD':%s, 'CMD_LOGIN_RECE':%s}"%(CMD_LOGIN, CMD_LOGIN_NO) #登录失败关键字 

DCT_REGISTER_OK = "{'msgCMD':%s, 'CMD_REGISTER_RECE':%s}"%(CMD_REGISTER, CMD_REGISTER_OK) #注册成功关键字
DCT_REGISTER_NO = "{'msgCMD':%s, 'CMD_REGISTER_RECE':%s}"%(CMD_REGISTER, CMD_REGISTER_NO) #注册失败关键字 


class userServer():
    def __init__(self):
        self.user_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    #注册登录
        self.user_socket.bind((SERVER_IP, USER_RECEIVE_PORT))                  #梆定端口3427
        self.user_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)   
    
    
    def startServer(self):
        try:
            threading.Thread(target=self.receUser).start()  #注册、登录
        except socket.error as msg:
            print ('注册、登录线程错误：%s '%msg)
    
    def receUser(self):
        while True:
            print('%s:%s Socket UDP服务器，等待接收注册或登录数据...'%(SERVER_IP, USER_RECEIVE_PORT))
            rec_msg, addr = self.user_socket.recvfrom(1024) #用户注册登录
            print('接收用户数据: ', rec_msg, addr)
            try:
                strdata = rec_msg.decode().strip()
                dct = toDict(strdata)
                cmd = dct.get("msgCMD", 0)
                if cmd == CMD_LOGIN:
                    self.login(dct, addr)
                elif cmd == CMD_REGISTER:
                    rec = json.dumps(dct)
                    self.regadd(dct, addr)
                else:
                    pass
                print('Time:', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') )
            except Exception as ex:
                print ('接收注册、登录数据错误：%s '%ex)


    def login(self, dct, addr):
        s = DCT_LOGIN_NO #登录失败关键字
        name = dct.get("name", "")
        password = dct.get("password", "")
        if is_name_pass(name, password, UserInfo):
            s = DCT_LOGIN_OK  #登录成功关键字
            print("登录成功 NAME=%s PASSWORD=%s"%(name, password))
        else:
            print("登录失败 NAME=%s PASSWORD=%s"%(name, password))
        self.user_socket.sendto(s.encode(),  addr) #发送登录关键字
        return ""

    def regadd(self, dct, addr):
        s = DCT_REGISTER_NO #注册失败关键字
        dct.pop("msgCMD")
        if addMac(dct, UserInfo): #写入数据库
            s = DCT_REGISTER_OK  #注册成功关键字
            print("注册成功！", find_all(UserInfo))
        else:
            print("注册失败！", find_all(UserInfo))
        self.user_socket.sendto(s.encode(),  addr) #发送注册关键字   
        return s.encode()
    
if __name__ == '__main__':
    user_server = userServer() #创建新服务器侦听连接
    threading.Thread(target=user_server.startServer).start()                    
